package com.example.onlinetaxi.ui.activity.MainPage.OrderFragments;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.Thread.IsDriverAgreeCancelThread;
import com.example.onlinetaxi.Thread.PassengerGetOrderStateThread;
import com.example.onlinetaxi.callback.DriverCallBack.ICancelCallBack;
import com.example.onlinetaxi.callback.OrderCallBack.GetOrderCallBack;
import com.example.onlinetaxi.callback.OrderCallBack.ReceivedOrderCallBack;
import com.example.onlinetaxi.dto.OrderDto.ReceivedOrderDto;
import com.example.onlinetaxi.ui.activity.DriverToStartPage.DriverToStartActivity;
import com.example.onlinetaxi.ui.activity.StartToEndPage.StartToEndActivity;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.view.Adapter.DoingOrderAdapter;
import com.example.onlinetaxi.view.Dialog.EditTextDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DoingOrderFragment extends Fragment {

    private View rootView;
    // 无订单提醒
    private TextView empty;
    // 订单列表
    private List<ReceivedOrderDto> orderList = new ArrayList<>();
    // 重新获取订单
    private GetOrderCallBack getOrderCallBack;
    // 列表
    private RecyclerView recyclerView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_doing_order, container, false);

        initView();

        initEvent();

        return rootView;
    }

    private void initView() {
        empty = rootView.findViewById(R.id.doing_order_empty);
        recyclerView = rootView.findViewById(R.id.doing_order_list);

        if (orderList.size() != 0) {
            empty.setVisibility(View.INVISIBLE);
        }
    }

    private void initEvent() {
        // 初始化订单列表控件
        initRecyclerView();

        // 初始化空页面
        if (orderList.size() != 0) {
            empty.setVisibility(View.INVISIBLE);
        } else {
            empty.setVisibility(View.VISIBLE);
        }
    }

    private void initRecyclerView() {
        // 找到布局文件中的recyclerView
        /*指定RecyclerView布局方式*/
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        /*指定为LinearLayout布局*/
        // 判断是否为主线程
        if (Looper.myLooper() == Looper.getMainLooper()) {
            recyclerView.setLayoutManager(layoutManager);
        }

        // 设置颜色配置
        DoingOrderAdapter.drawable = getResources().getDrawable(R.color.perfect_red);
        DoingOrderAdapter.drawable2 = getResources().getDrawable(R.color.perfect_blue);
        /*适配去管理滑动显示*/
        DoingOrderAdapter adapter = new DoingOrderAdapter(orderList);

        adapter.setReceivedOrderCallBack(new ReceivedOrderCallBack() {
            @Override
            public void jump(ReceivedOrderDto order) {
                // 点击订单页面跳转
                if ((order.getCancelState().equals("0") || order.getCancelState().equals("3") || order.getCancelState().equals("1")) & order.getState().equals("3")) {
                    // 跳转到等待接车
                    startActivity(new Intent(getActivity(), DriverToStartActivity.class));
                } else if ((order.getCancelState().equals("0") || order.getCancelState() == null || order.getCancelState().equals("3")) & order.getState().equals("4")) {
                    // 跳转到前往终点界面
                    startActivity(new Intent(getActivity(), StartToEndActivity.class));
                }
            }

            @Override
            public void clickButton(ReceivedOrderDto order) {
                // 取消订单按钮
                // 弹出输入框--输入取消原因
                showDialog(order);
            }
        });

        /*设置适配*/
        if (Looper.myLooper() == Looper.getMainLooper()) {
            recyclerView.setAdapter(adapter);
        }
    }

    private void showDialog(ReceivedOrderDto orderDto) {
        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 取消，不操作
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击确认
                // 关闭获取状态线程
                PassengerGetOrderStateThread.finished = true;
                // 关闭线程
                PassengerGetOrderStateThread.thread = null;

                // 向后端发送取消清单请求
                sendCancelOrderRequest(orderDto);

                Toast.makeText(getActivity(), "撤销申请已发送!请等待司机响应!", Toast.LENGTH_SHORT).show();

                // 刷新界面
                refresh();

                // 开启线程监听司机是否同意取消
                IsDriverAgreeCancelThread.iCancelCallBack = new ICancelCallBack() {
                    @Override
                    public void cancelCallBack(String state) {
                        // 对state进行判断
                        if (state.equals("2")) {
                            // 司机同意
                            // 删除保存本地的订单数据
                            LocalStorage.chosenOrder = null;
                            LocalStorage.currentOrderId = null;
                            LocalStorage.currentOrder = null;

                            Looper.prepare();
                            refresh();
                            Toast.makeText(getActivity(), "司机同意了您的撤销请求！", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        } else if (state.equals("3")) {
                            // 司机拒绝
                            // 重启获取司机是否接到乘客线程
                            PassengerGetOrderStateThread.finished = false;
                            PassengerGetOrderStateThread.thread = new Thread(new PassengerGetOrderStateThread.GetReceivedOrderState(getActivity(), StartToEndActivity.class));
                            PassengerGetOrderStateThread.thread.start();

                            Looper.prepare();
                            refresh();
                            Toast.makeText(getActivity(), "司机拒绝了您的撤销请求！", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    }
                };
                IsDriverAgreeCancelThread.finished = false;
                IsDriverAgreeCancelThread.thread = new Thread(new IsDriverAgreeCancelThread.GetOrderState());
                IsDriverAgreeCancelThread.thread.start();
            }
        };

        // 显示提示框
        EditTextDialog.showInfoDialog(getActivity(), "撤销原因", "取消撤销", onCancelClickListener, "确认撤销", onConfirmClickListener);
    }

    private void sendCancelOrderRequest(ReceivedOrderDto orderDto) {
        Map<String, String> map = new HashMap<>();

        map.put("orderId", orderDto.getReceivedOrderId().toString());
        map.put("cancelReason", EditTextDialog.Builder.cancelReason.getText().toString());

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "cancelOrderRequest");
    }

    public void setGetOrderCallBack(GetOrderCallBack getOrderCallBack) {
        this.getOrderCallBack = getOrderCallBack;
    }

    private void refresh() {
        // 重新获取order列表
        getOrderCallBack.refreshOrder();

        // 刷新当前页面
        initEvent();
    }

    public void setOrderList(List<ReceivedOrderDto> orderList) {
        this.orderList = orderList;
    }
}